package com.qyer.lxp.service.task;

import com.qyer.lxp.common.date.DateUtil;
import com.qyer.lxp.common.framework.contants.QyerContants;
import com.qyer.lxp.common.framework.core.BaseSpringService;
import com.qyer.lxp.common.framework.util.QyerConfig;
import com.qyer.lxp.service.mail.ISendEmailService;
import com.qyer.lxp.model.product.normal.*;
import com.qyer.lxp.model.product.parameter.ProductInfoRequest;
import com.qyer.lxp.service.price.IPriceService;
import com.qyer.lxp.service.product.IProductService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by wangzhen on 16/6/2.
 */
@Component("productTaskService")
public class ProductTaskService extends BaseSpringService{

    @Resource
    private IProductService productService;

    @Resource
    private IPriceService priceService;

    @Resource
    private ISendEmailService sendEmailService;

    /**
     * 存储更新的内容 key:productCode  value:更改的属性，更改的内容
     */
    private Map<String,Map<String,String>> mapUpdate=new HashMap<String,Map<String,String>>();

    /**
     * 存储下架内容
     */
    private List<String> listDown=new ArrayList<String>();



    /**
     * 定时服务类
     */
    public void startProductTask(){
        if(QyerConfig.getInstance().getBoolean(QyerContants.QYER_PRICE_IS_FULL_UPDATE,true)){
            //选品商品全量更新
            Map<String, String> mapProduct = productService.getProductCode(2);
            for(String productCode:mapProduct.keySet()){
                //删除相关所有数据
                productService.deleteProductBookQuestion(productCode);

                productService.deleteProductInfo(productCode);

                productService.deleteProductBookQuestion(productCode);

                productService.deleteProductDescn(productCode);

                productService.deleteProductExtendPropertie(productCode);

                productService.deleteProductInclude(productCode);

                productService.deleteProductItinerary(productCode);

                productService.deleteProductItineraryHotel(productCode);

                productService.deleteProductItineraryTraffic(productCode);

                productService.deleteProductPhoto(productCode);

                productService.deleteProductSpecfication(productCode);

                productService.deleteSaleItemDetail(productCode);

                productService.deleteSaleItemAdditionalOption(productCode);

                productService.deleteSaleItemAddressDetail(productCode);

                productService.deleteSaleItemVoucherInfo(productCode);

                productService.insertProduct(productCode,mapProduct.get(productCode));
            }
        }else{
            //获取选品商品昨天更新的数据
            Map<String, String> mapProduct = productService.getProductCode(3);
            if (null != mapProduct && mapProduct.size() > 0) {
                for (String productCode : mapProduct.keySet()) {
                    Map<String, String> mapProperty = new HashMap<String, String>();//存储更改的属性以及内容
                    boolean isUpdate = false;//未更新
                    ProductInfoRequest productInfoRequest = new ProductInfoRequest();
                    try {
                        productInfoRequest.setProductCode(productCode);
                        productInfoRequest.setCurrency("CNY");
                        productInfoRequest.setNeedSaleInfo("true");
                        ProductInfo productInfo = productService.getProductInfo(productInfoRequest);
                        String salePoints_str = "";

                        if (null!=mapProduct.get(productCode)&&mapProduct.get(productCode).equals("OFF_SHELF")) {
                            listDown.add(productCode);
                        }
                        if (null != productInfo) {
                            productInfo.setFromtime(DateUtil.getCurrentDateTimeToStr3());
                            if (mapProduct.get(productCode).equals("RELEASE") || mapProduct.get(productCode).equals("UPDATE")) {
                                productInfo.setStatus(1);
                            } else if (mapProduct.get(productCode).equals("OFF_SHELF")) {
                                productInfo.setStatus(2);
                            }

                            //产品卖点
                            if (null != productInfo.getSalePoints()) {
                                List<String> listSalePoint = productInfo.getSalePoints();
                                for (String points : listSalePoint) {
                                    salePoints_str = salePoints_str + points + "|";
                                }
                                salePoints_str = salePoints_str.substring(0, salePoints_str.lastIndexOf("|"));
                            }

                            //产品卖点
                            productInfo.setSalePoints_str(salePoints_str);
                            try {
                                ProductInfo productInfo_old = productService.getProductInfo(productCode);
                                if (null != productInfo_old) {
                                    //判断标题是否更改
                                    if (null!=productInfo.getProductName()&&!productInfo.getProductName().equals(productInfo_old.getProductName())) {
                                        mapProperty.put("sku标题", productInfo.getProductName());
                                        isUpdate = true;
                                    }
                                    //判断国家是否更改
                                    if (null!=productInfo.getCountryName()&&!productInfo.getCountryName().equals(productInfo_old.getCountryName())) {
                                        mapProperty.put("目的地-国家", productInfo.getCountryName());
                                        isUpdate = true;
                                    }
                                    //判断城市是否更改
                                    if (null!=productInfo.getCityName()&&!productInfo.getCityName().equals(productInfo_old.getCityName())) {
                                        mapProperty.put("目的地-城市", productInfo.getCityName());
                                        isUpdate = true;
                                    }
                                    //判断价格是否更改
//                                    if (null!=productInfo.getNetPriceFrom()&&!productInfo.getNetPriceFrom().equals(productInfo_old.getNetPriceFrom())) {
//                                        System.out.println("1:"+productInfo.getNetPriceFrom()+"----"+productInfo_old.getNetPriceFrom());
//                                        mapProperty.put("供应价（净价）", productInfo.getNetPriceFrom());
//                                        isUpdate = true;
//                                    }
//                                    //判断建议零售价是否更改
//                                    if (null!=productInfo.getRetailPriceFrom()&&!productInfo.getRetailPriceFrom().equals(productInfo_old.getRetailPriceFrom())) {
//                                        mapProperty.put("建议零售价", productInfo.getRetailPriceFrom());
//                                        isUpdate = true;
//                                    }
                                    //判断费用包含是否更改
                                    if (null!=productInfo.getInclusions()&&!productInfo.getInclusions().equals(productInfo_old.getInclusions())) {
                                        mapProperty.put("费用包含", productInfo.getInclusions());
                                        isUpdate = true;
                                    }
                                    //判断费用不含是否更改
                                    if (null!=productInfo.getExclusions()&&!productInfo.getExclusions().equals(productInfo_old.getExclusions())) {
                                        mapProperty.put("费用不含", productInfo.getExclusions());
                                        isUpdate = true;
                                    }
                                    //判断集合信息是否更改
                                    if (null!=productInfo.getDepartureRemark()&&!productInfo.getDepartureRemark().equals(productInfo_old.getDepartureRemark())) {
                                        mapProperty.put("集合信息", productInfo.getDepartureRemark());
                                        isUpdate = true;
                                    }
                                    //判断解散信息是否更改
                                    if (null!=productInfo.getDropOffRemark()&&!productInfo.getDropOffRemark().equals(productInfo_old.getDropOffRemark())) {
                                        mapProperty.put("解散信息", productInfo.getDropOffRemark());
                                        isUpdate = true;
                                    }
                                    //判断预定须知是否更改
                                    if (null!=productInfo.getAttentions()&&!productInfo.getAttentions().equals(productInfo_old.getAttentions())) {
                                        mapProperty.put("预定须知", productInfo.getAttentions());
                                        isUpdate = true;
                                    }
                                    //判断产品特色是否更改
                                    if (null!=productInfo.getSalePoints_str()&&!productInfo.getSalePoints_str().equals(productInfo_old.getSalePoints_str())) {
                                        mapProperty.put("产品特色", productInfo.getSalePoints_str());
                                        isUpdate = true;
                                    }

                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                logger.error(e);
                            }

                            //销售项目详细信息
                            if (null != productInfo.getSaleItemDetails()) {
                                if (null != productInfo.getSaleItemDetails().getSaleItemDetailList()) {
                                    List<SaleItemDetail> listDetail = productInfo.getSaleItemDetails().getSaleItemDetailList();
                                    String book_str = "";//预定方式

                                    String supply_str = "";//出票方式

                                    String valid_time_desc_str = "";//有效期描述

                                    String restriction_str = "";//限制条件
                                    for (SaleItemDetail model : listDetail) {
                                        String s = model.getBookMethod();
                                        if (s.equals("NO_CONFIRM")) {
                                            book_str = "立即确认";
                                        } else if (s.equals("NEED_CONFIRM")) {
                                            book_str = "需要确认";
                                        } else if (s.equals("API_NEED_CONFIRM")) {
                                            book_str = "需要确认";
                                        }

                                        String s1 = model.getSupplyMethod();
                                        if (s1.equals("NO_CONFIRM")) {
                                            supply_str = "立即确认";
                                        } else if (s1.equals("NEED_CONFIRM")) {
                                            supply_str = "需要确认";
                                        } else if (s1.equals("API_NEED_CONFIRM")) {
                                            supply_str = "需要确认";
                                        }
                                        valid_time_desc_str = model.getValidTimeDesc();
                                        restriction_str = model.getRestriction();
                                        if (null == restriction_str || restriction_str.equals("")) {
                                            continue;
                                        }

                                        SaleItemDetail model_old = productService.getSaleItemDetailBySaleCode(model.getSaleCode());
                                        if (null != model_old) {
                                            //判断套餐标题是否更改
                                            if (null!=model.getSaleName()&&!model.getSaleName().equals(model_old.getSaleName())) {
                                                mapProperty.put("套餐标题-" + model.getSaleCode(), model.getSaleName());
                                                isUpdate = true;
                                            }
                                        }
                                        break;

                                    }


                                    String book_str_old = "";//预定方式

                                    String supply_str_old = "";//出票方式

                                    String valid_time_desc_str_old = "";//有效期描述

                                    String restriction_str_old = "";//限制条件
                                    List<SaleItemDetail> listDetail_old = productService.getSaleItemDetail(productCode);//获取数据库里的记录
                                    for (SaleItemDetail model : listDetail_old) {
                                        String s = model.getBookMethod();
                                        if (s.equals("NO_CONFIRM")) {
                                            book_str_old = "立即确认";
                                        } else if (s.equals("NEED_CONFIRM")) {
                                            book_str_old = "需要确认";
                                        } else if (s.equals("API_NEED_CONFIRM")) {
                                            book_str_old = "需要确认";
                                        }

                                        String s1 = model.getSupplyMethod();
                                        if (s1.equals("NO_CONFIRM")) {
                                            supply_str_old = "立即确认";
                                        } else if (s1.equals("NEED_CONFIRM")) {
                                            supply_str_old = "需要确认";
                                        } else if (s1.equals("API_NEED_CONFIRM")) {
                                            supply_str_old = "需要确认";
                                        }
                                        valid_time_desc_str_old = model.getValidTimeDesc();
                                        restriction_str_old = model.getRestriction();
                                        if (null == restriction_str_old || restriction_str_old.equals("")) {
                                            continue;
                                        }

                                        break;

                                    }

                                    //判断产品特色是否更改
                                    if (null!=book_str&&!book_str.equals(book_str_old)) {
                                        mapProperty.put("产品概要-预定方式", book_str);
                                        isUpdate = true;
                                    }

                                    //判断出票方式是否更改
                                    if (null!=supply_str&&!supply_str.equals(supply_str_old)) {
                                        mapProperty.put("产品概要-出票方式", supply_str);
                                        isUpdate = true;
                                    }

                                    //判断有效期描述是否更改
                                    if (null!=valid_time_desc_str&&!valid_time_desc_str.equals(valid_time_desc_str_old)) {
                                        mapProperty.put("产品概要-有效期描述", valid_time_desc_str);
                                        isUpdate = true;
                                    }

                                    //判断限制条件是否更改
                                    if (null!=restriction_str&&!restriction_str.equals(restriction_str_old)) {
                                        mapProperty.put("产品概要-限制条件", restriction_str);
                                        isUpdate = true;
                                    }

                                }
                            }

                        }
                        if (isUpdate) {//有更新
                            //将更新内容存入内存
                            mapUpdate.put(productCode, mapProperty);
                        }

                        //删除相关所有数据
                        productService.deleteProductBookQuestion(productCode);

                        productService.deleteProductInfo(productCode);

                        productService.deleteProductBookQuestion(productCode);

                        productService.deleteProductDescn(productCode);

                        productService.deleteProductExtendPropertie(productCode);

                        productService.deleteProductInclude(productCode);

                        productService.deleteProductItinerary(productCode);

                        productService.deleteProductItineraryHotel(productCode);

                        productService.deleteProductItineraryTraffic(productCode);

                        productService.deleteProductPhoto(productCode);

                        productService.deleteProductSpecfication(productCode);

                        productService.deleteSaleItemDetail(productCode);

                        productService.deleteSaleItemAdditionalOption(productCode);

                        productService.deleteSaleItemAddressDetail(productCode);

                        productService.deleteSaleItemVoucherInfo(productCode);

                        //执行数据重新入库
                        productService.insertProduct(productCode,mapProduct.get(productCode));


                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error(e);
                        logger.error("错误code" + productCode);
                    }
                }
                String historyDate=DateUtil.getPreviousDateTimeString("yyyy-MM-dd");

                StringBuffer html_content=new StringBuffer();
                html_content.append("<html>\n");
                html_content.append("<head>\n");
                html_content.append("<meta charset=\"utf-8\"/>\n");
                html_content.append("  <title>\n");
                html_content.append("    力行产品信息更新\n");
                html_content.append("  </title>\n");
                html_content.append("</head>\n");
                html_content.append("<body style=\"padding:0; margin:0;\">\n");
                html_content.append("<table style=\" padding:0; margin:0 auto; font-family:'microsoft YAHEI'; color:#555;\" width=\"880\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n");
                html_content.append("  <tr>\n");
                html_content.append("    <td>\n");
                html_content.append("      <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n");
                html_content.append("            <tbody>\n");
                html_content.append("              <tr>\n");
                html_content.append("                <td style=\"background: #fff; padding: 20px 20px; font-size:24px; color:#333;\">\n");
                html_content.append("                      力行产品信息更新|"+historyDate+"\n");
                html_content.append("                </td>\n");
                html_content.append("              </tr>\n");
                html_content.append("          </table>\n");
                html_content.append("    </td>\n");
                html_content.append("  </tr>\n");
                html_content.append("  <tr>\n");
                html_content.append("    <td><strong style=\"background:#ddd; display:block; margin:0; padding:0 20px; line-height:44px; font-size:18px;\">产品相关更新信息</strong></td>\n");
                html_content.append("  </tr>\n");
                html_content.append("  <tr>\n");
                html_content.append("    <td style=\"padding-top:20px;\">\n");
                html_content.append("      <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"border:1px solid #ddd; border-collapse:collapse;\">\n");
                html_content.append("            <tr>\n");
                if (null != mapUpdate && mapUpdate.size() > 0) {
                    for (String productCode : mapUpdate.keySet()) {
                        html_content.append("               <th style=\"background:#FF3333; font-size:14px; line-height:32px; border:1px solid #ccc;\" width=\"180\">产品code</th>\n");
                        html_content.append("               <th style=\"background:#FF3333; font-size:14px; line-height:32px; border:1px solid #ccc;\">"+productCode+"</th>\n");
                        html_content.append("             </tr>\n");
                        html_content.append("             <tr>\n");
                        Map<String, String> maps = mapUpdate.get(productCode);
                        if (null != maps && maps.size() > 0) {
                            for (String title : maps.keySet()) {
                                html_content.append("              <th style=\"background:#eee; font-size:14px; line-height:32px; border:1px solid #ccc;\">"+title+"</th>\n");
                                html_content.append("              <th style=\"background:#eee; font-size:14px; line-height:32px; border:1px solid #ccc;\">"+ maps.get(title)+"</th>\n");
                                html_content.append("            </tr>\n");
                            }
                        }
                    }
                }



                html_content.append( "      </table>\n");
                html_content.append("    </td>\n");
                html_content.append("  </tr>\n");
                html_content.append("</table>\n");
                html_content.append("</body>\n");
                html_content.append("</html>");

                //邮件报警更新产品
                if(null!=mapUpdate&&mapUpdate.size()>0){
                    try {
                        sendEmailService.sendEmail("力行产品信息更新|"+historyDate,html_content.toString(),QyerConfig.getInstance().getString("qyer.mail.productInfo"));
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error(e);
                    }
                }


                //邮件报警下架产品
                if(null!=listDown&&listDown.size()>0){
                    StringBuffer sbDown=new StringBuffer("下架产品：");
                    for(String code:listDown){
                        sbDown.append(code).append(",");
                    }
                    sbDown.toString().substring(0,sbDown.lastIndexOf(","));
                    try {
                        sendEmailService.sendEmail("力行产品下架|"+historyDate,sbDown.toString(),QyerConfig.getInstance().getString("qyer.mail.productInfo"));
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error(e);
                    }
                }

            }
        }
        mapUpdate.clear();
        logger.info("商品信息更新完成");
    }
}
